﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace Presentation.Web.Core.Cookie
{
    public static class CookieManager
    {
        const string CookieKey = "Presentation.Web_CookieManager";

        /// <summary>
        /// Gets the cookie value.
        /// </summary>
        /// <param name="key">Name of the cookie.</param>
        /// <returns></returns>
        public static string GetCookieValue(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieKey];
            if (cookie != null)
            {
                return cookie[key];
            }
            return null;
        }
        /// <summary>
        /// Sets the cookie value.
        /// </summary>
        /// <param name="key">Name of the cookie.</param>
        /// <param name="value">The cookie value.</param>
        public static void SetCookieValue(string key, string value)
        {
            // Set the response cookie and copy all request cookies to the response
            HttpCookie cookie = HttpContext.Current.Response.Cookies[CookieKey];
            if (cookie == null || !cookie.HasKeys)
            {
                cookie.Expires = System.DateTime.Now.AddYears(1);
                cookie.Domain = Regex.Match(HttpContext.Current.Request.Url.Host, @"^(.* \.)* (?<MAINDOMAIN>.*? \. .*?)$", RegexOptions.IgnorePatternWhitespace).Groups["MAINDOMAIN"].Value;
                foreach (string existingKey in HttpContext.Current.Request.Cookies[CookieKey].Values.AllKeys)
                {
                    string existingVal = HttpContext.Current.Request.Cookies[CookieKey].Values[existingKey];
                    cookie[existingKey] = existingVal;
                }
            }
            cookie[key] = value;
            // Set the request cookie
            cookie = HttpContext.Current.Request.Cookies[CookieKey];
        }
    }
}
